package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    BehaviorFeign behaviorFeign;

    /**保存用户搜索记录
     *
     * @param dto
     */
    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDTO dto) {
       //获取参数
        Integer entryId = dto.getEntryId();
        String searchWords = dto.getSearchWords();
        //查询行为实体
        ResponseResult<ApBehaviorEntry> entryResponseResult = behaviorFeign.findByUserIdOrEquipmentId(entryId, dto.getEquipmentId());
        //判断是否存在行为实体
        if(!entryResponseResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取行为实体数据
        ApBehaviorEntry behaviorEntry = entryResponseResult.getData();
        if(behaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询当前用户搜索的关键词是否存在
        ApUserSearch apUserSearches = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(entryId).and("keyword").is(searchWords)), ApUserSearch.class);
        //存在则更新索引库中的数据   不存在则保存
        if (apUserSearches != null) {
            apUserSearches.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearches);
            return;
        }
        //3.2 不存在则新增
        apUserSearches = new ApUserSearch();
        apUserSearches.setCreatedTime(new Date());
        apUserSearches.setEntryId(behaviorEntry.getId());
        apUserSearches.setKeyword(searchWords);
        mongoTemplate.save(apUserSearches);

    }

    /**查询用户搜索记录  显示10条
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        //判断是否传入搜索事件 若没有则更新为当前时间
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        //创建新集合 泛型为ApUserSearch  用来存储用户的搜索记录
        List<ApUserSearch> userSearchList = new ArrayList<>();
        //先定义查询的长度
        int size = 10;
        //调用线程  查询用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //远程调用接口  查询行为实体
        ResponseResult<ApBehaviorEntry> behaviorEntryResponseResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if(behaviorEntryResponseResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //获取查询到的行为实体
        ApBehaviorEntry apBehaviorEntry = behaviorEntryResponseResult.getData();

        if(apBehaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //若存在则查询当前用户搜索列表
        if(apBehaviorEntry!= null){
            userSearchList =
                    //根据行为实体id 创建时间做为查寻条件
            mongoTemplate.find(Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("createdTime").lt(dto.getMinBehotTime()))
                    //按照时间降序排序
                    .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                    //分页  只查十条
                    .limit(size),ApUserSearch.class);

            return ResponseResult.okResult(userSearchList);

        }
        return ResponseResult.okResult(userSearchList);
    }

    /**删除搜索记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {

        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorEntryResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if(!behaviorEntryResult.checkCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorEntryResult.getData();
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }

        //执行删除方法
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(dto.getId()).and("entryId").is(behaviorEntry.getId())),ApUserSearch.class);

        return ResponseResult.okResult();
    }
}
